<?php

use \Workerman\Worker;
use \Workerman\WebServer;
use \GatewayWorker\Gateway;
use \GatewayWorker\BusinessWorker;
use \Workerman\Autoloader;
use \GatewayWorker\Lib\Db;
use \GatewayWorker\Lib\Store;

require_once __DIR__ . '/../../Workerman/Autoloader.php';
Autoloader::setRootPath(__DIR__);

$gateway               = new Gateway("websocket://0.0.0.0:9999");
$gateway->name         = 'Kefu';
$gateway->count        = 4;
$gateway->lanIp        = '127.0.0.1';
$gateway->startPort    = 5300;
$gateway->pingInterval = 10;
$gateway->pingData     = '{"type":"ping"}';

$gateway->onWorkerStart = function ($gateway) {

    // 重置redis
    Store::instance('kf')->delete(Store::instance('kf')->keys('kf_bind_*'));
    Store::instance('kf')->delete(Store::instance('kf')->keys('kf_group_*'));

};

$gateway->onConnect = function ($connection) {

    $connection->onWebSocketConnect = function ($connection, $http_header) {

        // 需改成redis

        //$result  = Store::instance('kf')->get('kf_domains');
        //$domains = json_decode($result, 1);
        //
        //if (!in_array(getdomain($_SERVER['HTTP_ORIGIN']), $domains)) {
        //
        //    $connection->close();
        //}

    };

};

if (!defined('GLOBAL_START')) {
    Worker::runAll();
}

function getdomain($url) {

    $host = strtolower($url);

    if (strpos($host, '/') !== false) {
        $parse = @parse_url($host);
        $host  = $parse ['host'];
    }

    $topleveldomaindb = array(
        'com', 'edu', 'gov', 'int', 'mil', 'net', 'org', 'biz', 'info', 'pro', 'name', 'museum', 'coop', 'aero', 'xxx', 'idv', 'mobi', 'cc', 'me'
    );

    $str = '';
    foreach ($topleveldomaindb as $v) {
        $str .= ($str ? '|' : '') . $v;
    }
    $matchstr = "[^\.]+\.(?:(" . $str . ")|\w{2}|((" . $str . ")\.\w{2}))$";

    if (preg_match("/" . $matchstr . "/ies", $host, $matchs)) {
        $domain = $matchs ['0'];
    } else {
        $domain = $host;
    }

    return $domain;
}